from models.BaseModel import BaseModel
from peewee import *
from entry.Entrys import Page
from util.Model2Dict import m2d
""" 系统日志 """
class SysHandleLog(BaseModel):
    lId = BigIntegerField(db_column='l_id',primary_key= True)
    handleName = CharField(db_column='handle_name')
    time = DateTimeField()
    key = CharField()
    resp = TextField()
    req = TextField()
    username = CharField()
    status = IntegerField()
    ip = CharField()
    token = CharField()
    path = CharField()
    hid = BigIntegerField()
    class Meta:
        table_name = 'sys_handle_log'
        
""" 获取所有的日志信息 """
def getAllHandleLog(page:Page = Page(),cdn:dict=dict(),ids:list[int]=None):
    query = SysHandleLog.select()
    if cdn.get('username'):
        query = query.where(SysHandleLog.username.startswith(cdn.get('username')))
    if cdn.get('hid'):
        query = query.where(SysHandleLog.hid.in_(cdn.get('hid')))
    if ids!=None:
        query = query.where(SysHandleLog.hid.in_(ids))
    if cdn.get('time'):
        t:list[str] = cdn.get('time')
        if t[0]:
            query = query.where(SysHandleLog.time > t[0])
        if t[1]:
            query = query.where(SysHandleLog.time < t[1])
    if cdn.get('order'):
        order:dict = cdn.get('order')
        if order.get('time') and order.get('time')=='asc':
            query = query.order_by(SysHandleLog.time.asc())
        if order.get('time') and order.get('time')=='desc':
            query = query.order_by(SysHandleLog.time.desc())
    if page == None:
        r = query.dicts()
        return m2d(r)
    else:
        r = query.paginate(page.num,page.size).dicts()
        page.count = query.count()
        page.rows = m2d(r)
        return page.__dict__

""" 更新某个日志的属性 """
def updateHandleLog(id:int,k):
    return SysHandleLog.update(k).where(SysHandleLog.lId == id).execute() > 0
""" 删除某日志 """
# 按条件清除
def clearLog(lids:list[int]=None,cdn:dict = dict()):
    q = SysHandleLog.delete()
    if lids!=None:
        q = q.where(SysHandleLog.lId.in_(lids))
    if cdn.get('username'):
        q = q.where(SysHandleLog.username == cdn.get('username'))
    if cdn.get('hids'):
        q = q.where(SysHandleLog.hid.in_(cdn.get('hids')))
    q.execute()
    return True
""" 添加某日志 """
def addHandleLog(d:dict):
    return SysHandleLog.insert(d).execute() 
